package com.cndw.kongfu.ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.Vector;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JToolBar;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import com.cndw.kongfu.config.Constants;
import com.cndw.kongfu.config.HostConfig;
import com.cndw.kongfu.config.SimulateData;
import com.cndw.kongfu.model.ChatData;
import com.cndw.kongfu.net.Connector;

public class MainFrame extends JFrame{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1636022358901247845L;

	//private JLabel title = new JLabel("KongFu");
	
	private JSplitPane leftJSplitPane;
	
	private JSplitPane downJSplitPane;
	
	private DataTable dataTable;
	
	//����б�ĵ�JScrollPane
	private JScrollPane tablePane;
	
	//��������JScrollPane
	private JScrollPane treePane;
	
	//������
	private JTree tree;
	
	//������ʾJTextArea
	private JTextArea chatTextArea = new JTextArea(10, 80);
	
	//������ʾ��JScrollPane, �����ʾ���ݵ�JTextArea
	private JScrollPane chatScrollPane;

	//������
	private JToolBar toolBar = new JToolBar();
	
	private boolean connected = false;
	
	private Connector connector = null;
	
	private JLabel msg = new JLabel("�ѶϿ�");
	
	//����б�
	private List<ChatData> data = SimulateData.getSimulateData();;
	
	private Action conn = new AbstractAction("����", new ImageIcon("images/in.gif")) {
		public void actionPerformed(ActionEvent e) {
			if(connected) {
				connector.disconnect();
				connected = false;
				msg.setText("�ѶϿ�");
			} else {
				connector = new Connector(HostConfig.host, HostConfig.port);
				connector.connect();
				connected = true;
				msg.setText("������");
			}
		}
	};
	

	public MainFrame() {
		super();
		init();
	}
	
	public void init() {
		this.tree = createTree();
		final DefaultTableModel tableMode = new DefaultTableModel();
		this.dataTable = new DataTable(tableMode);
		tableMode.setDataVector(createViewDatas(data), getListColumn());
		
		setTableFace();//���ñ����ʽ
		this.tablePane = new JScrollPane(this.dataTable);
		this.tablePane.setBackground(Color.WHITE);
		
		this.chatTextArea.setLineWrap(true);
		this.chatTextArea.setEditable(false);
		this.chatTextArea.setFont(new Font(null, Font.BOLD, 14));
		this.chatScrollPane =  new JScrollPane(this.chatTextArea);
		
		//�б��������Ϣ��JSplitPane
		this.downJSplitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, 
				this.tablePane, chatScrollPane);
		this.downJSplitPane.setDividerLocation(600);
		this.downJSplitPane.setDividerSize(20);
		
		//����JScrollPane
		this.treePane = new JScrollPane(this.tree);
		
		this.leftJSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, 
				this.treePane, this.downJSplitPane);
		this.leftJSplitPane.setDividerLocation(150);
		this.leftJSplitPane.setDividerSize(3);
		
		//����������
		createToolBar();
		//����JFrame�ĸ�������
		this.add(leftJSplitPane);
		this.setTitle("KongFu�ͻ���");
		this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		this.pack();
		this.setExtendedState(JFrame.MAXIMIZED_BOTH);
		//this.setMinimumSize(new Dimension(800, 600));
		initListeners();
		
		Thread updatetThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				int i = 0;
				while (i++ < 100) {
					tableMode.addRow(createViewDatas(SimulateData.getSimulateData()));
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		updatetThread.start();
		
	}
	
	private void initListeners() {
		//�б�ѡ�������
		this.dataTable.getSelectionModel().addListSelectionListener(new ListSelectionListener(){
			public void valueChanged(ListSelectionEvent event) {
				//��ѡ����ʱ����ͷ�ʱ��ִ��
				if (!event.getValueIsAdjusting()) {
					//���û��ѡ���κ�һ��, �򷵻�
					if (dataTable.getSelectedRowCount() != 1) return;
					view();
				}
			}
		});
	}
	
	public void view() {
		// TODO Auto-generated method stub
		int row = this.dataTable.getSelectedRow();
		//System.out.println(row);
	}

	//������������
	private JTree createTree() {
		//������ڵ�
		DefaultMutableTreeNode root = new DefaultMutableTreeNode();
		//��������ӽڵ�
		root.add(new DefaultMutableTreeNode(new ChatNode()));
		
		//������
		JTree tree = new JTree(root);
		//������������
		tree.addMouseListener(new SailTreeListener(this));
		//���ظ�ڵ�
		tree.setRootVisible(false);
		//���ýڵ㴦����
		SailTreeCellRenderer cellRenderer = new SailTreeCellRenderer();
		tree.setCellRenderer(cellRenderer);
		return tree;
	}
	
	public void select() {
		AbstractNode selectedNode = getSelectNode();
		//TODO
		//System.out.println(selectedNode.getText());
	}
	
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private Vector getListColumn() {
		Vector columns = new Vector();
		columns.add(Constants.TABLE_CLUMN_ID);
		columns.add(Constants.TABLE_CLUMN_NAME);
		columns.add(Constants.TABLE_CLUMN_CHAT);
		columns.add(Constants.TABLE_CLUMN_DATE);
		columns.add(Constants.TABLE_CLUMN_FORBID);
		return columns;
	}
	
	@SuppressWarnings({"rawtypes" })
	private Vector<Vector> createViewDatas(List<ChatData> data) {
		Vector<Vector> views = new Vector<Vector>();
		for (ChatData e : data) {
			Vector<Object> view = new Vector<Object>();
			view.add(e.getId());
			view.add(e.getName());
			view.add(e.getChat());
			view.add(e.getDate());
			view.add("");
			
			views.add(view);
		}
		return views;
	}
	
	//�����б����ʽ
	private void setTableFace() {
		this.dataTable.setCellSelectionEnabled(true);
		DefaultTableCellRenderer render = new DefaultTableCellRenderer();
	    render.setHorizontalAlignment(SwingConstants.CENTER);

		this.dataTable.getColumn(Constants.TABLE_CLUMN_ID).setMinWidth(80);
		this.dataTable.getColumn(Constants.TABLE_CLUMN_ID).setMaxWidth(80);
		//�����������
		this.dataTable.getColumn(Constants.TABLE_CLUMN_ID).setCellRenderer(render);
		this.dataTable.getColumn(Constants.TABLE_CLUMN_NAME).setMinWidth(100);
		this.dataTable.getColumn(Constants.TABLE_CLUMN_NAME).setCellRenderer(render);
		this.dataTable.getColumn(Constants.TABLE_CLUMN_CHAT).setMinWidth(600);
		this.dataTable.getColumn(Constants.TABLE_CLUMN_DATE).setMinWidth(130);
		this.dataTable.getColumn(Constants.TABLE_CLUMN_DATE).setCellRenderer(render);
		this.dataTable.getColumn(Constants.TABLE_CLUMN_FORBID).setMinWidth(40);
		
		TableColumnModel tcm = dataTable.getColumnModel();
        //tcm.setColumnMargin(10);
        JButton bun = new JButton(Constants.BTN_FORBID);
        bun.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JButton bun=(JButton)e.getSource();
                bun.setText(Constants.BTN_FORBID);
                //TODO
            }
        });
        tcm.getColumn(4).setCellEditor(new DefaultCellEditor(bun));
	
		DefaultTableCellRenderer dtcr = new DefaultTableCellRenderer(){
            public Component getTableCellRendererComponent(JTable table, Object value,
                    boolean isSelected, boolean hasFocus, int row, int column) {
                Component c = table.getCellEditor(row, column).getTableCellEditorComponent(table, null, isSelected, row, column);
                if(c instanceof JButton){
                    JButton cBun = (JButton)c;
                    Object text = table.getModel().getValueAt(row, column);
                    
                    JButton bun = new JButton(Constants.BTN_FORBID);
                    bun.setPreferredSize(cBun.getPreferredSize());
                    bun.setForeground(cBun.getForeground());
                    bun.setBackground(cBun.getBackground());
                    bun.setFont(cBun.getFont());
                    return bun;
                }
                return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
            }
        };
        
        tcm.getColumn(4).setCellRenderer(dtcr);
		
		this.dataTable.setRowHeight(25);
		//this.dataTable.set
	}
	
	//��ʼ��������
	private void createToolBar() {
		this.toolBar.add(this.conn).setToolTipText("����");
		this.toolBar.add(msg);
		this.add(this.toolBar, BorderLayout.NORTH);
	}
	
	//��õ�ǰѡ�е�box
	private AbstractNode getSelectNode() {
		TreePath treePath = this.tree.getSelectionPath();
		if (treePath == null) return null;
		//���ѡ�е�TreeNode
		DefaultMutableTreeNode node = (DefaultMutableTreeNode)treePath.getLastPathComponent();
		return (AbstractNode)node.getUserObject();
	}
}
